package com.woniuxy.sddfp.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.woniuxy.sddfp.common.constant.redis.RedisConstant;
import com.woniuxy.sddfp.sms.config.SmsTemplate;
import com.woniuxy.sddfp.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SmsTemplate smsTemplate;

    @Override
    public String sendCode(String phone) {

        String key = RedisConstant.SMS_PREFIX + phone;

        if (stringRedisTemplate.hasKey(key)){
            String redisCode = stringRedisTemplate.opsForValue().get(key);
            log.info("验证码已发送，验证码为：{}",redisCode);
            return redisCode;
        }
        String code = RandomUtil.randomNumbers(4);
        // 验证码存储到redis
        stringRedisTemplate.opsForValue().set(key,code, Duration.ofMinutes(5));
        // 调用阿里云sms服务，发送验证码
       //smsTemplate.sendSms(phone,code);
        log.info("发送验证码成功，验证码为：{}",code);

        return code;

    }
}
